<template>
  <a-row class="video-layout" type="flex" justify="space-around">
    <a-col :xl="15" :lg="24" :md="24" :sm="24" :xs="24">
      <a-card>
        <a-row type="flex" justify="space-between" style="height:480px;background:white">
          <a-col :span="4">
            <Tools
              class="tools"
              @changeSize="changeSize"
              @changeColor="changeColor"
              @handleBack="back"
              @handleClear="clear"
              @handleSave="save"
            ></Tools>
          </a-col>
          <a-col :span="20" class="layer" id="screen">
            <a-col :span="24" class="mark-layer">
              <canvas id="canvas"></canvas>
            </a-col>
            <a-col
              :span="24"
              class="video-layer"
              id="video-layer"
              style="height:350px;width:630px;position:relative"
            >
              <video
                id="video"
                height="350px"
                width="630px"
                controls="controls"
                style="position:absolute"
              >
                <!-- <source src="../assets/video.mp4" type="video/mp4" /> -->
                <source
                  src="http://139.9.118.119:9999/video/download/?filename=test.mp4"
                  type="video/mp4"
                />
              </video>
            </a-col>
            <a-col :span='24' style="margin-top:5px;">
            <a-row type='flex' align='center' style="width:630px;height:46px;padding:5px;border:1px solid grey;">
              <a-col :span='19'>
              <a-form id="formDanmu" ref="formDanmu" :form="formDanmu" @submit="handleSubmitDanmu">
                <a-form-item>
                  <a-input
                    type="text"
                    placeholder="请输入弹幕"
                    v-decorator="['msg', {rules: [{ required: false, pattern: /[A-Za-z]{2,20}|[\u4e00-\u9fa5]{1,10}/, message: '弹幕为空' }], validateTrigger: 'blur'}]"
                  />
                </a-form-item>
              </a-form>
              </a-col>
              <a-col :span='5'><a-button style="width:100%" @click="handleSubmitDanmu">发弹幕</a-button></a-col>
            </a-row>
            </a-col>
          </a-col>
        </a-row>
      </a-card>
    </a-col>
    <a-col style="padding: 0 12px" :xl="8" :lg="24" :md="24" :sm="24" :xs="24">
      <a-card
        title="个人信息"
        style="margin-bottom: 24px"
        :bordered="true"
        :body-style="{padding: '15px'}"
      >
        <a-col :span="11" :gutter="10">
          <a-col :span="12">运动员编码：</a-col>
          <a-col :span="12">{{$store.state.athleteid}}</a-col>
        </a-col>
        <a-col :span="11" :gutter="10">
          <a-col :span="12">运动员姓名：</a-col>
          <a-col :span="12">{{$store.state.athletename}}</a-col>
        </a-col>
        <a-col :span="11" v-for="(item,i) in bodydata" :key="item.name" :gutter="10">
          <a-col :span="12">{{item.name}}：</a-col>
          <a-col :span="12">{{ item.data }}</a-col>
        </a-col>
      </a-card>
      <a-card
        title="运动员近期成绩"
        style="margin-bottom: 24px"
        :bordered="true"
        :body-style="{padding: '15px'}"
      >
        <Chart id="radar" :data="radar" style="height:250px;width:100%"></Chart>
      </a-card>
    </a-col>
    <a-col :span="15">
      <a-col :span="12">
        <a-card
          title="重心高度变化"
          style="margin-bottom: 24px"
          :bordered="true"
          :body-style="{padding: '15px'}"
        >
          <Chart id="height" :data="height" style="height:300px;width:100%"></Chart>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card
          title="双手双脚间距变化"
          style="margin-bottom: 24px"
          :bordered="true"
          :body-style="{padding: '15px'}"
        >
          <Chart id="HandFeet" :data="handfeet" style="height:300px;width:100%"></Chart>
        </a-card>
      </a-col>
    </a-col>
    <a-col :span="8">
      <a-card
        title="杠铃高度变化"
        style="margin-bottom: 24px"
        :bordered="true"
        :body-style="{padding: '15px'}"
      >
        <Chart id="heightChange" :data="heightChange" style="height:300px;width:100%"></Chart>
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import Tools from "../components/Tools";
import Chart from "../components/chart";
import "html2canvas";
import Danmaku from "danmaku";
export default {
  data() {
    return {
      formDanmu: this.$form.createForm(this),
      height: {
        backgroundColor: "transparent",
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: [
            "2s",
            "3s",
            "4s",
            "5s",
            "6s",
            "7s",
            "8s",
            "9s",
            "10s",
            "11s",
            "12s",
            "13s",
            "14s",
            "15s"
          ]
        },

        yAxis: [
          {
            type: "value"
          }
        ],
        series: [
          {
            name: "双脚",
            type: "line",
            symbol: "circle",
            symbolSize: 4,
            itemStyle: {
              normal: {
                color: "red",
                borderColor: "red" //拐点边框颜色
              }
            },
            data: [
              220,
              182,
              191,
              234,
              290,
              330,
              310,
              220,
              182,
              191,
              234,
              290,
              330,
              310
            ]
          }
        ]
      },
      heightChange: {
        backgroundColor: "transparent",
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: [
            "2s",
            "3s",
            "4s",
            "5s",
            "6s",
            "7s",
            "8s",
            "9s",
            "10s",
            "11s",
            "12s",
            "13s",
            "14s",
            "15s"
          ]
        },

        yAxis: [
          {
            type: "value"
          }
        ],
        series: [
          {
            name: "双脚",
            type: "line",
            symbol: "circle",
            symbolSize: 4,
            itemStyle: {
              normal: {
                color: "red",
                borderColor: "red" //拐点边框颜色
              }
            },
            data: [
              220,
              182,
              191,
              234,
              290,
              330,
              310,
              220,
              182,
              191,
              234,
              290,
              330,
              310
            ]
          }
        ]
      },
      handfeet: {
        backgroundColor: "transparent",
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: [
            "2s",
            "3s",
            "4s",
            "5s",
            "6s",
            "7s",
            "8s",
            "9s",
            "10s",
            "11s",
            "12s",
            "13s",
            "14s",
            "15s"
          ]
        },

        yAxis: [
          {
            type: "value"
          }
        ],
        series: [
          //虚线
          {
            name: "双手",
            type: "line",
            symbolSize: 4, //拐点圆的大小
            color: ["red"], //折线条的颜色
            data: [
              1000,
              300,
              500,
              800,
              300,
              600,
              500,
              800,
              300,
              500,
              800,
              300,
              600,
              500
            ],
            smooth: false, //关键点，为true是不支持虚线的，实线就用true
            itemStyle: {
              normal: {
                lineStyle: {
                  width: 2,
                  type: "dotted" //'dotted'虚线 'solid'实线
                }
              }
            }
          },
          //实线
          {
            name: "双脚",
            type: "line",
            symbol: "circle",
            symbolSize: 4,
            itemStyle: {
              normal: {
                color: "red",
                borderColor: "red" //拐点边框颜色
              }
            },
            data: [
              220,
              182,
              191,
              234,
              290,
              330,
              310,
              220,
              182,
              191,
              234,
              290,
              330,
              310
            ]
          }
        ]
      },
      radar: {
        backgroundColor: "transparent",
        tooltip: {
          //雷达图的tooltip不会超出div，也可以设置position属性，position定位的tooltip 不会随着鼠标移动而位置变化，不友好
          confine: true,
          enterable: true //鼠标是否可以移动到tooltip区域内
        },
        radar: {
          splitNumber: 3, // 雷达图圈数设置
          name: {
            textStyle: {
              color: "#838D9E"
            }
          },
          // 设置雷达图中间射线的颜色
          axisLine: {
            lineStyle: {
              color: "rgba(131,141,158,.1)"
            }
          },
          indicator: [
            {
              name: "04-27",
              max: 30,
              //若将此属性放在radar下，则每条indicator都会显示圈上的数值，放在这儿，只在通信这条indicator上显示
              axisLabel: {
                show: true,
                fontSize: 12,
                color: "#838D9E",
                showMaxLabel: false, //不显示最大值，即外圈不显示数字30
                showMinLabel: true //显示最小数字，即中心点显示0
              }
            },
            { name: "04-28", max: 30 },
            { name: "04-29", max: 30 },
            { name: "04-30", max: 30 },
            { name: "05-01", max: 30 }
          ],
          //雷达图背景的颜色，在这儿随便设置了一个颜色，完全不透明度为0，就实现了透明背景
          splitArea: {
            show: false,
            areaStyle: {
              color: "rgba(255,0,0,0)" // 图表背景的颜色
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              width: 1,
              color: "rgba(131,141,158,.1)" // 设置网格的颜色
            }
          }
        },
        series: [
          {
            name: "雷达图", // tooltip中的标题
            type: "radar", //表示是雷达图
            symbol: "circle", // 拐点的样式，还可以取值'rect','angle'等
            symbolSize: 8, // 拐点的大小

            areaStyle: {
              normal: {
                width: 1,
                opacity: 0.2
              }
            },
            data: [
              {
                value: [7, 18, 19, 13, 20],
                name: "",
                itemStyle: {
                  normal: {
                    color: "rgba(255,74,74,.3)",
                    lineStyle: {
                      width: 1,
                      color: "rgba(255,74,74,.3)"
                    }
                  }
                }
              }
            ]
          }
        ]
      },
      bodydata: [
        { name: "体重", data: "47" },
        { name: "身高", data: "158" },
        { name: "肩宽", data: "70" },
        { name: "BMI", data: "18" },
        { name: "体脂率", data: "18" }
      ],
      lineWidth: 10,
      color: "#666",
      canvas: null,
      context: null,
      danmu:null,
      drawing: false,
      myTimeStamp: undefined,
      minTimeDiff: 8, // 值越大 记录的点越少
      minPointDistance: 8,
      stack: [],
      path: []
    };
  },
  components: {
    Tools,
    Chart
  },
  mounted() {
    this.init();
  },
  methods: {
    handleSubmitDanmu(item) {
      this.formDanmu.validateFields((err, values) => {
        if (!err) {
          this.emitDanmu(values.msg)
          this.formDanmu.resetFields();
        }
      });
    },
    emitDanmu(str){
      this.danmaku.emit({
        text: str,

        // 默认为 rtl（从右到左），支持 ltr、rtl、top、bottom。
        mode: "rtl",

        // 弹幕显示的时间，单位为秒。
        // 在使用媒体模式时，如果未设置，会默认为音视频的当前时间；实时模式不需要设置。
        // time: 10,

        // 在使用 DOM 引擎时，Danmaku 会为每一条弹幕创建一个 <div> 节点，
        // style 对象会直接设置到 `div.style` 上，按 CSS 规则来写。
        // 例如：
        style: {
          fontSize: "20px",
          color: "#ffffff",
          border: "1px solid #337ab7",
          textShadow:
            "-1px -1px #000, -1px 1px #000, 1px -1px #000, 1px 1px #000"
        },

        // 在使用 canvas 引擎时，Danmaku 会为每一条弹幕创建一个 <canvas> 对象，
        // 需要按 CanvasRenderingContext2D 对象的格式来写。
        // 例如：
        style: {
          font: "20px sans-serif",
          textAlign: "start",
          // 注意 bottom 是默认的
          textBaseline: "bottom",
          direction: "inherit",
          fillStyle: "#000",
          strokeStyle: "#000",
          lineWidth: 1.0
          // ...
        }
      });
    },
    changeSize(newSize) {
      this.lineWidth = newSize;
    },
    changeColor(newColor) {
      this.color = newColor;
    },
    init() {
      this.canvas = document.getElementById("canvas");
      this.context = this.canvas.getContext("2d");
      this.setCanvasSize();
      this.context.lineCap = "round";
      this.context.lineJoin = "round";
      this.context.fillStyle = "#ffffff00";
      this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
      // window.onresize = this.setCanvasSize;
      this.canvas.addEventListener("mousedown", this.handleMousedown);
      this.canvas.addEventListener("touchstart", this.handleTouchstart);
      this.danmaku = new Danmaku({
        // 必填。用于显示弹幕的「舞台」会被添加到该容器中。
        container: document.getElementById("video-layer"),

        // 媒体可以是 <video> 或 <audio> 元素，如果未提供，会变成实时模式。
        media: document.getElementById("video"),

        // 预设的弹幕数据数组，在媒体模式中使用。在 emit API 中有说明格式。
        comments: [],

        // 支持 DOM 引擎和 canvas 引擎。canvas 引擎比 DOM 更高效，但相对更耗内存。
        // 完整版本中默认为 DOM 引擎。
        engine: "canvas",

        // 弹幕速度，也可以用 speed API 设置。
        speed: 144
      });
    },
    setCanvasSize() {
      this.canvas.width = 630;
      this.canvas.height = 290;
    },
    handleMousedown(e) {
      this.drawing = true;
      this.myTimeStamp = new Date().getTime();
      let x = e.clientX - this.canvas.getBoundingClientRect().left,
        y = e.clientY - this.canvas.getBoundingClientRect().top;
      console.log(e);
      this.path.push({ width: this.lineWidth, color: this.color });
      this.path.push({ x, y });
      this.stack.push(this.path);
      this.drawLine();
      this.canvas.addEventListener("mousemove", this.handleMousemove);
      this.canvas.addEventListener("mouseup", this.handleMouseup);
    },
    handleMousemove(e) {
      // 类似函数节流 控制笔迹数量
      if (new Date().getTime() - this.myTimeStamp < this.minTimeDiff) {
        return;
      }
      let x = e.clientX - this.canvas.getBoundingClientRect().left,
        y = e.clientY - this.canvas.getBoundingClientRect().top;
      console.log(e, x, y);
      // 判断两个点是否太靠近 太近的点不要
      let x0 = this.path[this.path.length - 1].x,
        y0 = this.path[this.path.length - 1].y;
      if (
        Math.abs(x - x0) < this.minPointDistance &&
        Math.abs(y - y0) < this.minPointDistance
      ) {
        return;
      }
      this.path.push({ x, y });
      this.stack.pop();
      this.stack.push(this.path);
      this.drawLine();
      this.myTimeStamp = new Date().getTime();
    },
    handleMouseup() {
      this.drawing = false;
      this.path = [];
      this.canvas.removeEventListener("mousemove", this.handleMousemove);
      this.canvas.removeEventListener("mouseup", this.handleMouseup);
    },
    handleTouchstart(e) {
      e.preventDefault();
      this.drawing = true;
      this.myTimeStamp = new Date().getTime();
      let x = e.touches[0].clientX - this.canvas.getBoundingClientRect().left,
        y = e.touches[0].clientY - this.canvas.getBoundingClientRect().top;
      console.log(e, x, y);
      this.path.push({ width: this.lineWidth, color: this.color });
      this.path.push({ x, y });
      this.stack.push(this.path);
      this.drawLine();
      this.canvas.addEventListener("touchmove", this.handleTouchmove);
      this.canvas.addEventListener("touchend", this.handleTouchend);
    },
    handleTouchmove(e) {
      e.preventDefault();
      // 类似函数节流 控制笔迹数量
      if (new Date().getTime() - this.myTimeStamp < this.minTimeDiff) {
        return;
      }
      let x = e.touches[0].clientX - this.canvas.getBoundingClientRect().left,
        y = e.touches[0].clientY - this.canvas.getBoundingClientRect().top;
      console.log(e, x, y);

      // 判断两个点是否太靠近 太近的点不要
      let x0 = this.path[this.path.length - 1].x,
        y0 = this.path[this.path.length - 1].y;
      if (
        Math.abs(x - x0) < this.minPointDistance &&
        Math.abs(y - y0) < this.minPointDistance
      ) {
        return;
      }
      this.path.push({ x, y });
      this.stack.pop();
      this.stack.push(this.path);
      this.drawLine();
      this.myTimeStamp = new Date().getTime();
    },
    handleTouchend(e) {
      e.preventDefault();
      this.drawing = false;
      this.path = [];
      document.removeEventListener("mousemove", this.handleTouchmove);
      document.removeEventListener("mouseup", this.handleTouchend);
    },
    drawLine() {
      // this.context.fillStyle = "#ffffff00";
      this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
      console.log(this.path, this.stack);
      this.stack.forEach(path => {
        let length = path.length;
        path.forEach((value, index, array) => {
          if (index === 0) {
            // 这条线的样式
            this.context.lineWidth = value.width;
            this.context.strokeStyle = value.color;
          } else if (index === 1) {
            // 第一个点
            this.context.beginPath();
            this.context.moveTo(value.x, value.y);
            this.context.lineTo(value.x, value.y);
          } else {
            // 贝塞尔优化
            let x1 = array[index - 1].x,
              y1 = array[index - 1].y,
              x2 = value.x,
              y2 = value.y;
            let x3 = x1 / 2 + x2 / 2,
              y3 = y1 / 2 + y2 / 2;
            this.context.quadraticCurveTo(x1, y1, x3, y3);
          }
          if (index === length - 1) {
            this.context.lineTo(value.x, value.y);
            this.context.stroke();
          }
        });
      });
    },
    back() {
      console.log("back");
      this.stack.splice(this.stack.length - 1, 1);
      this.path.length = 0;
      this.drawLine();
    },
    clear() {
      console.log("clear");
      this.path.length = 0;
      this.stack.length = 0;
      this.drawLine();
    },
    save() {
      let a = document.createElement("a");
      this.context.drawImage(this.canvas, 0, 0, 630, 410);
      a.href = this.canvas.toDataURL("image/png");
      (a.download = "note.jpg"), document.body.appendChild(a);
      a.click();
      a.remove();
    }
  }
};
</script>

<style>
#tool {
  display: inline-flex;
  flex-direction: column;
  width: 8%;
  height: 350px;
  margin-right: 2%;
  border: 2px solid gray;
}
#column {
  display: flex;
  height: 350px;
  flex-direction: column;
}
#column div {
  flex-grow: 1;
  width: 100%;
  border: 2px solid rgb(62, 103, 197);
}
#column div:nth-child(2) {
  margin-top: 10px;
}
#chart {
  display: inline-block;
  height: 180px;
  width: 40%;
  margin-top: 20px;
  background: rgb(255, 255, 255);
  border: 2px solid rgb(107, 213, 107);
}
#chart:nth-child(2) {
  margin-left: 10%;
}
.layer {
  position: relative;
}
.video-layer {
  position: absolute;
  z-index: 1;
}
.mark-layer {
  position: absolute;
  z-index: 2;
}
</style>